package com.kehutong.basic.annex.service;

import com.kehutong.basic.annex.entity.OperateRecord;
import com.kehutong.basic.annex.enums.BusinessType;
import com.kehutong.basic.annex.enums.OperateType;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.util.Enums;
import org.coraframework.util.Objects;

@WebService("/basic/operate/record/service")
public class OperateRecordService {

    @Inject
    private JdbcSession jdbcSession;

    public Object page(JSONObject jsonObject) {
        String businessType = jsonObject.getString("businessType");
        String businessId = jsonObject.getString("businessId");
        if (Objects.isEmpty(businessType) && Objects.isEmpty(businessId)) {
            return Result.error(0, "请输入必填参数");
        }

        return Result.success(jdbcSession.findPage(OperateRecord.class)
                .eq(jsonObject, "businessType", "businessId")
                .order("createTime", "desc")
                .page(jsonObject)
                .exe());
    }

    @ReqMapping("/save")
    public Object save(JSONObject jsonObject) {
        OperateRecord entity = getOperateRecord(jsonObject);
        jdbcSession.insert(entity);
        return Result.success();
    }

    @ReqMapping("/batch/save")
    public Object save(JSONArray jsonArray) {
        for (Object obj: jsonArray) {
            JSONObject jsonObject = (JSONObject)obj;
            OperateRecord entity = getOperateRecord(jsonObject);
            jdbcSession.insert(entity);
        }
        return Result.success();
    }

    private OperateRecord getOperateRecord(JSONObject jsonObject) {
        OperateRecord entity = Pool.newInstance(OperateRecord.class);

        String businessId = jsonObject.getString("businessId");
        entity.setBusinessId(businessId);

        BusinessType businessType = Enums.getEnum(BusinessType.class, jsonObject.getString("businessType"));
        entity.setBusinessType(businessType);

        entity.setOperateDesc(jsonObject.getString("operateDesc"));
        entity.setOperateName(jsonObject.getString("operateName"));
        entity.setOperateNo(jsonObject.getString("operateNo"));

        OperateType operateType = Enums.getEnum(OperateType.class, jsonObject.getString("operateType"));
        entity.setOperateType(operateType);

        return entity;
    }
}
